using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class ColorPicker : MonoBehaviour, IPointerDownHandler, IDragHandler
{
    public Image colorImage;
    public Image pointer;
    public Color CurrentColor { get; private set; } = Color.white;

    private RectTransform rectTransform;
    private Texture2D colorTexture;

    void Start()
    {
        rectTransform = GetComponent<RectTransform>();
        CreateColorTexture();
    }

    private void CreateColorTexture()
    {
        colorTexture = new Texture2D(256, 256);
        colorImage.sprite = Sprite.Create(colorTexture, new Rect(0, 0, 256, 256), Vector2.zero);

        for (int y = 0; y < 256; y++)
        {
            for (int x = 0; x < 256; x++)
            {
                float h = (float)x / 255f;
                float s = 1f;
                float v = 1f - (float)y / 255f;
                colorTexture.SetPixel(x, y, Color.HSVToRGB(h, s, v));
            }
        }
        colorTexture.Apply();
    }

    public void OnPointerDown(PointerEventData eventData)
    {
        UpdateColor(eventData);
    }

    public void OnDrag(PointerEventData eventData)
    {
        UpdateColor(eventData);
    }

    private void UpdateColor(PointerEventData eventData)
    {
        Vector2 localPoint;
        if (RectTransformUtility.ScreenPointToLocalPointInRectangle(
            rectTransform, eventData.position, eventData.pressEventCamera, out localPoint))
        {
            float x = (localPoint.x + rectTransform.rect.width / 2) / rectTransform.rect.width;
            float y = (localPoint.y + rectTransform.rect.height / 2) / rectTransform.rect.height;

            x = Mathf.Clamp01(x);
            y = Mathf.Clamp01(y);

            pointer.rectTransform.anchoredPosition = new Vector2(
                x * rectTransform.rect.width - rectTransform.rect.width / 2,
                y * rectTransform.rect.height - rectTransform.rect.height / 2);

            int texX = Mathf.FloorToInt(x * colorTexture.width);
            int texY = Mathf.FloorToInt(y * colorTexture.height);

            CurrentColor = colorTexture.GetPixel(texX, texY);
        }
    }
}
